<template>
    <div class="container">
      <form @submit.prevent="handleSubmit">
        <div class="mb-3">
          <label for="file" class="form-label">选择文件:</label>
          <input 
            type="file" 
            class="form-control" 
            id="file" 
            name="file" 
            required 
            @change="handleFileChange"
          />
        </div>
        <button type="submit" class="btn btn-primary">上传</button>
      </form>
    </div>
  </template>
  
  <script>
  export default {
    name: "OssUploader",
    data() {
      return {
        selectedFile: null
      };
    },
    methods: {
      handleFileChange(event) {
        this.selectedFile = event.target.files[0];
      },
      async handleSubmit(event) {
        if (!this.selectedFile) {
          alert('请选择一个文件再上传。');
          return;
        }
  
        try {
          // 获取签名 - 使用Axios
          const signatureResponse = await this.$api.serviceOSS.get(
            "/get_post_signature_for_oss_upload"
          );
          
          const data = signatureResponse.data;
          const formData = new FormData();
          
          // 准备表单数据
          formData.append("success_action_status", "200");
          formData.append("policy", data.policy);
          formData.append("x-oss-signature", data.signature);
          formData.append("x-oss-signature-version", "OSS4-HMAC-SHA256");
          formData.append("x-oss-credential", data.x_oss_credential);
          formData.append("x-oss-date", data.x_oss_date);
          formData.append("key", data.dir + this.selectedFile.name);
          formData.append("x-oss-security-token", data.security_token);
          formData.append("file", this.selectedFile); // file 必须为最后一个表单域
  
          // 调试信息
          console.log("上传URL:", "https://quickknowledgepicturestorage.oss-cn-hangzhou.aliyuncs.com/" + 
            data.dir + this.selectedFile.name);
        
        this.$api.serviceUser.post('api/user/modifyUserPic', 
        {userAccount: this.$store.state.user.userAccount, 
            userPic: "https://quickknowledgepicturestorage.oss-cn-hangzhou.aliyuncs.com/" + 
            data.dir + this.selectedFile.name}, 
            {
            headers: {
            'Content-Type': 'application/json'
            }
        })
        .then(response => {
        })
        .catch(error => {
            console.log('失败', error);
        });

            // 上传文件 - 使用Axios
            const uploadResponse = await this.$api.serviceUser.post(
                data.host,
                formData,
                {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
                }
            );
  
          if (uploadResponse.status === 200) {
            console.log("上传成功");
            alert("文件已上传");
          } else {
            console.log("上传失败", uploadResponse);
            alert("上传失败，请稍后再试");
          }
        } catch (error) {
          console.error("发生错误:", error);
          alert("上传过程中发生错误");
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
  }
  </style>